const fs = require("fs");
const { basename } = require("path");
const Oss = require("ali-oss");

class AliOssManager {
  constructor({ region, accessKeyId, accessKeySecret, bucket, folder = "" }) {
    this.client = new Oss({
      region,
      accessKeyId,
      accessKeySecret,
      bucket,
    });
    this.folder = folder;
  }
  async uploadFile(localPath) {
    try {
      const stream = fs.createReadStream(localPath);
      const size = fs.statSync(localPath).size;
      const name = `${this.folder}${basename(localPath)}`;
      const { res = {} } = await this.client.putStream(name, stream, {
        contentLength: size,
      });
      return { code: res.statusCode };
    } catch (error) {
      return { code: -1 };
    }
  }
  async deleteFile(filePath) {
    try {
      // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
      const name = `${this.folder}${basename(filePath)}`;
      const { res } = await this.client.delete(name);
      return { code: res.statusCode };
    } catch (e) {
      return { code: -1 };
    }
  }
}

module.exports = AliOssManager;
